package com.example.projectmanagement.service.study;

import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.study.Course;
import com.example.projectmanagement.model.study.CourseEnrollment;
import com.example.projectmanagement.model.study.EnrollmentStatus;
import com.example.projectmanagement.repository.study.CourseEnrollmentRepository;
import com.example.projectmanagement.repository.study.CourseRepository;
import com.example.projectmanagement.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class CourseEnrollmentService {
    
    @Autowired
    private CourseEnrollmentRepository courseEnrollmentRepository;
    
    @Autowired
    private CourseRepository courseRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    public CourseEnrollment applyForEnrollment(Long userId, Long courseId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));
        
        // 检查是否已经申请过
        Optional<CourseEnrollment> existingEnrollment = courseEnrollmentRepository.findByUserAndCourse(user, course);
        if (existingEnrollment.isPresent()) {
            throw new RuntimeException("Already applied for enrollment");
        }
        
        CourseEnrollment enrollment = new CourseEnrollment();
        enrollment.setUser(user);
        enrollment.setCourse(course);
        enrollment.setStatus(EnrollmentStatus.PENDING);
        enrollment.setCreatedAt(LocalDateTime.now());
        enrollment.setUpdatedAt(LocalDateTime.now());
        
        return courseEnrollmentRepository.save(enrollment);
    }
    
    public CourseEnrollment approveEnrollment(Long enrollmentId) {
        CourseEnrollment enrollment = courseEnrollmentRepository.findById(enrollmentId)
                .orElseThrow(() -> new RuntimeException("Enrollment not found"));
        
        enrollment.setStatus(EnrollmentStatus.APPROVED);
        return courseEnrollmentRepository.save(enrollment);
    }
    
    public CourseEnrollment rejectEnrollment(Long enrollmentId) {
        CourseEnrollment enrollment = courseEnrollmentRepository.findById(enrollmentId)
                .orElseThrow(() -> new RuntimeException("Enrollment not found"));
        
        enrollment.setStatus(EnrollmentStatus.REJECTED);
        return courseEnrollmentRepository.save(enrollment);
    }
    
    public CourseEnrollment revokeApproval(Long enrollmentId) {
        CourseEnrollment enrollment = courseEnrollmentRepository.findById(enrollmentId)
                .orElseThrow(() -> new RuntimeException("Enrollment not found"));
        
        enrollment.setStatus(EnrollmentStatus.PENDING);
        return courseEnrollmentRepository.save(enrollment);
    }
    
    public List<CourseEnrollment> getEnrollmentsByCourse(Long courseId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));
        return courseEnrollmentRepository.findByCourse(course);
    }
    
    public List<CourseEnrollment> getEnrollmentsByUserAndStatus(Long userId, EnrollmentStatus status) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        return courseEnrollmentRepository.findByUserAndStatus(user, status);
    }
    
    public List<CourseEnrollment> getAllEnrollmentsByUser(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        return courseEnrollmentRepository.findByUser(user);
    }
    
    public boolean isUserEnrolled(Long userId, Long courseId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));
        
        Optional<CourseEnrollment> enrollment = courseEnrollmentRepository.findByUserAndCourse(user, course);
        return enrollment.isPresent() && 
               enrollment.get().getStatus() == EnrollmentStatus.APPROVED;
    }
    
    public CourseEnrollment getUserEnrollment(Long userId, Long courseId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));
        
        Optional<CourseEnrollment> enrollment = courseEnrollmentRepository.findByUserAndCourse(user, course);
        return enrollment.orElse(null);
    }
    
    public Optional<CourseEnrollment> getEnrollmentByUserAndCourse(Long userId, Long courseId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));
        
        return courseEnrollmentRepository.findByUserAndCourse(user, course);
    }
}